<template>
  <div class="addressList app-container" v-loading="exportLoading">
    <div>
      <div
        class="addressMenu"
        :style="isManage ? 'height: calc(100vh - 150px);' : ''"
        v-if="!isProvince"
      >
        <AddressMenu
          :addressList="addressList"
          @menuClick="menuClick"
          :isManage="isManage"
          ref="menuIndex"
        />
      </div>
      <div class="addressTable" :style="isProvince ? 'width: 100%' : ''">
        <div
          class="dataList"
          v-loading="dataLoading"
          :style="
            isManage ? 'height: calc(100vh - 180px);padding-bottom:40px' : ''
          "
        >
          <el-scrollbar
            class="scrollbar p-20px pt-0"
            wrap-class="scrollbar-wrapper"
            style="
              border: 1px solid #ddd;
              border-radius: 10px;
              transform: scale(1);
            "
            @scroll="scrollDistance"
          >
            <header
              class="filterHeader"
              :class="{ isFlexdBox: !isFlexd }"
              :style="!tableData.length ? 'top: 10px' : ''"
            >
              <div v-show="showFilter" class="flex items-center">
                <el-select
                  v-model="company"
                  placeholder="所属公司"
                  @change="changeCompany"
                  style="border-radius: 50%"
                >
                  <el-option
                    v-for="item in department"
                    :label="item.label"
                    :key="item.id"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="queryForm.jobPosition"
                  class="mx-15px"
                  placeholder="工作岗位"
                  @change="queryData"
                  clearable
                  style="border-radius: 50%"
                >
                  <el-option
                    v-for="item in jop_post_type"
                    :value="item?.value"
                    :label="item?.label"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="searchKeyword"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="关键词"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="keywordChange"
                  clearable
                  style="border-radius: 50%"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.employeeId"
                    :label="item.employeeName"
                    :value="item.employeeId"
                  />
                </el-select>
                <el-checkbox class="ml-15px mt-3px" v-model="columns[1].visible"
                  >职务</el-checkbox
                >
              </div>
              <div class="control">
                <!-- <el-tooltip
                  :content="tooltip"
                  placement="bottom"
                  effect="light"
                >
                  <svg-icon
                    icon-class="搜索"
                    :class="'text-20px cursor-pointer ml-10px'"
                    @click="hiddenFilter"
                  ></svg-icon>
                </el-tooltip> -->
                <span v-if="!isManage">
                  <el-tooltip
                    content="跳转通讯录管理"
                    placement="bottom"
                    effect="light"
                  >
                    <svg-icon
                      icon-class="编辑"
                      :class="'text-27px cursor-pointer translate-y-3px'"
                      @click="goToPage"
                      v-hasPermi="['system:address:manage']"
                    ></svg-icon>
                  </el-tooltip>
                </span>
                <span v-if="!isManage">
                  <el-tooltip
                    content="导出内容"
                    placement="bottom"
                    effect="light"
                  >
                    <svg-icon
                      icon-class="导出"
                      :class="'text-27px cursor-pointer translate-y-3px'"
                      @click="exportFile"
                    ></svg-icon>
                  </el-tooltip>
                </span>
              </div>
            </header>
            <div v-for="items in tableData" :key="items.companyName">
              <div v-for="d in items.data" :key="d.deptName">
                <div :span="24" class="bg-white">
                  <h1
                    class="color-#3379cc font-bold"
                    style="
                      border-bottom: 8px solid #3379cc;
                      padding-bottom: 13px;
                      margin: 20px 0 3px;
                    "
                  >
                    <span v-if="isProvince || isKeySearch"
                      >{{ items.companyName }}
                    </span>
                    <span v-if="isProvince || isKeySearch">(</span
                    >{{ d.deptName
                    }}<span v-if="isProvince || isKeySearch">)</span>
                  </h1>
                </div>
                <el-row class="flex pr-40px bg-#3379cc">
                  <template
                    v-for="(item, index) in [...columns, ...columns]"
                    :key="item.key + index"
                  >
                    <el-col
                      v-if="item.visible"
                      class="h-50px flex justify-center items-center text-16px font-bold"
                      :class="item.label === '手机号码' ? 'px-10px' : ''"
                      :span="columns[1].visible ? 3 : item.span"
                    >
                      {{ item.label }}</el-col
                    >
                  </template>
                </el-row>
                <template
                  v-for="(ds, index) in d.data"
                  :key="ds.deptId + index"
                >
                  <el-row
                    v-if="index < Math.ceil(d.data.length / 2)"
                    :class="{
                      'bg-#f7f7f7': index % 2 !== 0,
                      'min-h-50px': true
                    }"
                    class="items-center min-h-40px py-5px pr-40px"
                    style="border: 1px solid #ddd"
                  >
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="3"
                    >
                      {{ ds.employeeName }}</el-col
                    >
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="columns[1].visible ? 3 : 4"
                      v-if="columns[1].visible"
                    >
                      {{ ds.position }}</el-col
                    >
                    <el-col
                      class="flex justify-center items-center text-14px px-10px"
                      :span="columns[1].visible ? 3 : 4"
                    >
                      <span v-if="!isManage">{{ ds?.mobile }}</span>
                      <el-input
                        v-else
                        v-model="ds.mobile"
                        @change="val => changeItem(val, 'tel', ds)"
                        :class="{
                          changeBorderColor: ds.phoneFormalIsError
                        }"
                      ></el-input>
                    </el-col>
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="columns[1].visible ? 3 : 5"
                    >
                      <span v-if="!isManage">{{
                        jop_post_type
                          .filter(v => {
                            return (ds?.jobPosition || []).includes(v.value)
                          })
                          .map(v => v.label)
                          .toString()
                      }}</span>
                      <el-select
                        v-else
                        v-model="ds.jobPosition"
                        placeholder="工作岗位"
                        @change="val => changeItem(val, 'jop', ds)"
                        :multiple="true"
                        clearable
                        class="w-full"
                      >
                        <el-option
                          v-for="item in jop_post_type"
                          :value="item?.value"
                          :label="item?.label"
                        ></el-option>
                      </el-select>
                    </el-col>
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="3"
                    >
                      {{
                        d.data[index + Math.ceil(d.data.length / 2)]
                          ?.employeeName
                      }}</el-col
                    >
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="columns[1].visible ? 3 : 4"
                      v-if="columns[1].visible"
                    >
                      {{
                        d.data[index + Math.ceil(d.data.length / 2)]?.position
                      }}</el-col
                    >
                    <el-col
                      class="flex justify-center items-center text-14px px-10px"
                      :span="columns[1].visible ? 3 : 4"
                    >
                      <span v-if="!isManage">{{
                        d.data[index + Math.ceil(d.data.length / 2)]?.mobile
                      }}</span>
                      <el-input
                        :class="{
                          changeBorderColor:
                            d.data[index + Math.floor(d.data.length / 2)]
                              .phoneFormalIsError
                        }"
                        v-if="
                          isManage &&
                          index !== index + Math.floor(d.data.length / 2)
                        "
                        v-model="
                          d.data[index + Math.floor(d.data.length / 2)].mobile
                        "
                        @change="
                          val =>
                            changeItem(
                              val,
                              'tel',
                              d.data[index + Math.floor(d.data.length / 2)]
                            )
                        "
                      ></el-input>
                    </el-col>
                    <el-col
                      class="flex justify-center items-center text-14px"
                      :span="columns[1].visible ? 3 : 5"
                    >
                      <span v-if="!isManage">{{
                        jop_post_type
                          .filter(v => {
                            return (
                              d.data[index + Math.ceil(d.data.length / 2)]
                                ?.jobPosition || []
                            ).includes(v.value)
                          })
                          .map(v => v.label)
                          .toString()
                      }}</span>
                      <el-select
                        v-if="
                          isManage &&
                          index !== index + Math.floor(d.data.length / 2)
                        "
                        v-model="
                          d.data[index + Math.floor(d.data.length / 2)]
                            .jobPosition
                        "
                        placeholder="工作岗位"
                        @change="
                          val =>
                            changeItem(
                              val,
                              'jop',
                              d.data[index + Math.floor(d.data.length / 2)]
                            )
                        "
                        :multiple="true"
                        clearable
                        class="w-full"
                      >
                        <el-option
                          v-for="item in jop_post_type"
                          :value="item?.value"
                          :label="item?.label"
                        ></el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </template>
              </div>
            </div>
            <div
              class="w-full h-50vh flex justify-center items-center"
              v-if="!tableData.length"
            >
              <el-empty description="暂无数据" />
            </div>
          </el-scrollbar>
        </div>
      </div>

      <div v-if="isManage" class="saveBtn">
        <el-button type="primary" @click="saveRecords">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { getListWithRole } from '@/api/system/dept'
import { treeselectNoPriv } from '@/api/rsgl/zzjg'
import {
  getAddressList,
  getAddressEdit,
  exportAddress
} from '@/api/system/address'
import { getCurrentInstance } from 'vue'
import { jop_post_type } from '@/hooks/dict/contract'
import AddressMenu from './addressManage/index'

const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()

// 操作列显示隐藏
const columns = ref([
  { key: 0, label: '姓名', visible: true, span: 3 },
  { key: 1, label: '职务', visible: true, span: 3 },
  { key: 2, label: '手机号码', visible: true, span: 4 },
  { key: 3, label: '工作岗位', visible: true, span: 5 }
])
const addressName = ref('研发中心')
const department = ref([]) // 所属公司字典
const company = ref() // 公司id
const isManage = ref(false)
const isProvince = ref(false) //是否选择全省
watch(company, val => {
  isProvince.value = val === 100
})

async function init() {
  // 是否为通讯录管理页面
  isManage.value = !!location.href.match(/addressManage/)
  // 获取表格数据
  company.value = userStore.userInfo?.orgId
  getAddress()
  // 公司列表
  const res = await treeselectNoPriv()
  res.data[0].value = 100 // 全省id
  department.value = [res.data[0], ...res.data[0].children]
  department.value.forEach(v => {
    delete v.children
  })
}

const addressList = ref([])
const addressCompony = ref()

// 获取表格数据
const tableData = ref([])
const queryParams = ref()
async function getAddress(obj) {
  // 获取部门列表
  const res = await getListWithRole({ deptId: company.value })
  addressCompony.value = res.data.splice(0, 1)
  addressList.value = res.data
  let indexVal = '0'
  if (obj) {
    addressList.value.find((v, i) => {
      if (String(v.deptId) === String(obj.deptId)) {
        indexVal = String(i)
        return v
      }
    })
  }
  if (addressList.value.length || company.value === 100) {
    let params = {
      companyId: addressList.value[0]?.parentId,
      deptId: obj?.deptId || addressList.value[0]?.deptId
    }
    if (company.value === 100) {
      params = {}
      addressList.value = []
    }
    if (obj) {
      params = { search: obj.employeeName }
    }
    getTableData(params)
    // 获取请求数据参数
    proxy.$nextTick(() => {
      proxy.$refs.menuIndex.selectmenu(indexVal)
    })
  } else {
    tableData.value = []
  }
  addressName.value = addressList.value[Number(indexVal)]?.deptName
  deptId.value = addressList.value[Number(indexVal)]?.deptId
}

// 表格数据查询
const dataLoading = ref(false)
function getTableData(params) {
  dataLoading.value = true
  const data = {
    ...queryForm.value,
    ...params
  }
  if (queryForm.value.jobPosition) {
    data.jobPosition = queryForm.value.jobPosition.toString()
  } else {
    delete data.jobPosition
  }
  queryParams.value = data
  getAddressList(data)
    .then(res => {
      tableData.value = res.data
      tableData.value.forEach(v => {
        v.data.forEach(m => {
          m.data.forEach(n => {
            if (n.jobPosition) {
              n.jobPosition = n.jobPosition.split(',')
            }
          })
        })
      })
      // debugger
    })
    .finally(() => {
      dataLoading.value = false
    })
}

const queryForm = ref({})
function queryData(val) {
  searchKeyword.value = ''
  let params = {
    companyId: company.value
  }
  // 全省搜索
  if (company.value === 100) {
    delete params.companyId
  } else if (!val) {
    params.deptId = deptId.value
  }
  getTableData(params)
}

// 切换公司 切换通讯录目录
const menuIndex = ref()
function changeCompany(val) {
  searchKeyword.value = ''
  // 切换公司，删除工作岗位筛选条件
  queryForm.value.jobPosition = ''
  getAddress()
  // 切换公司保存工作岗位筛选条件
}

const deptId = ref()
// 目录点击事件
function menuClick(item) {
  addressName.value = item.deptName
  deptId.value = item.deptId
  searchKeyword.value = ''
  queryForm.value.jobPosition = ''
  getTableData({
    companyId: company.value,
    deptId: deptId.value
  })
}

// 保存修改
const saveList = ref({}) // tableItem change事件 储存数据
function changeItem(val, type, item) {
  console.log(...arguments, 123)
  if (item.mobile.length >= 11) {
    saveList.value[item.employeeId] = {
      mobile: item.mobile,
      jobPosition: item.jobPosition ? item.jobPosition.toString() : '',
      employeeId: item.employeeId,
      phoneFormalIsError: false
    }
    item.phoneFormalIsError = false
  } else if (item.mobile.length < 11 || !item.mobile) {
    saveList.value[item.employeeId] = {
      mobile: item.mobile,
      jobPosition: item.jobPosition ? item.jobPosition.toString() : '',
      employeeId: item.employeeId,
      phoneFormalIsError: true
    }
    item.phoneFormalIsError = true
  }
}

const errorTip = ref('')
function saveRecords() {
  const errorData = Object.values(saveList.value).filter((v, i) => {
    if (v.phoneFormalIsError) {
      return {
        data: v.phoneFormalIsError,
        index: i
      }
    }
  })
  if (errorData.length > 0) {
    proxy.$modal.msgError('手机号存在问题，请修改')
    return
  }

  const params = Object.values(saveList.value).filter(v => {
    if (!v.phoneFormalIsError) {
      return {
        mobile: v.mobile,
        jobPosition: v.jobPosition ? v.jobPosition.toString() : '',
        employeeId: v.employeeId
      }
    }
  })
  console.log(params.length, params, '1234')
  if (params.length) {
    getAddressEdit(params).then(res => {
      proxy.$modal.msgSuccess('保存成功')
      saveList.value = []
      errorTip.value = ''
      queryData()
    })
  }
}

// 远程检索
const searchKeyword = ref('')
const isKeySearch = ref(false) //是否关键词检索
watch(searchKeyword, val => {
  isKeySearch.value = !!val
})
const loading = ref(false)
const options = ref([])
// 控制请求 节流
const timing = ref(500)
const executeTime = ref(0)
function remoteMethod(query) {
  if (query) {
    const now = Date.now()
    if (!executeTime.value) {
      executeTime.value = now
    }
    if (now - executeTime.value < timing.value) {
      loading.value = true
      getAddressList({ search: query })
        .then(res => {
          console.log(res, '远程检索')
          // options.value
          const arr = []
          const op = res.data
          const ti = op.map(v => v.data)
          ti.forEach(v => {
            arr.push(...v)
          })
          const ons = arr.map(v => v.data)
          ons.forEach(v => {
            options.value.push(...v)
          })
        })
        .finally(() => {
          loading.value = false
          executeTime.value = 0
        })
    }
  } else {
    options.value = []
  }
}

// 关键词改变
function keywordChange(val) {
  if (val) {
    queryForm.value.jobPosition = ''
    const checkPersonData = options.value.find(v => {
      return String(v.employeeId) === String(val)
    })
    company.value = Number(checkPersonData.companyId)
    getAddress(checkPersonData, val)
    console.log(checkPersonData, '选中的数据')
  } else {
    getAddress()
  }
}

const tooltip = ref('隐藏筛选条件')
const showFilter = ref(true)
function hiddenFilter() {
  showFilter.value = !showFilter.value
  tooltip.value = showFilter.value ? '隐藏筛选条件' : '显示筛选条件'
  console.log(showFilter.value, 'showFilter')
}

function goToPage() {
  window.open('/rsgl/other/addressManage')
}

const exportLoading = ref(false)
function exportFile() {
  proxy.$modal.confirm('是否导出当前筛选项').then(() => {
    exportLoading.value = true
    proxy
      .downLoadByUrl('/system/address/export', queryParams.value, '通讯录表格')
      .finally(() => {
        exportLoading.value = false
      })
  })
}

// 获取滚动条滚动距离
const isFlexd = ref(true)
function scrollDistance({ scrollTop }) {
  console.log(scrollTop, 'scrollTop')
  if (isFlexd.value) {
    isFlexd.value = false
  }
  if (scrollTop === 0) {
    isFlexd.value = true
  }
}

init()
</script>

<style scoped lang="scss">
.addressList {
  .addressMenu {
    float: left;
    width: 240px;
    margin-right: 20px;
    // border: 1px solid #ddd;
    overflow: hidden;
  }
  .addressTable {
    @apply float-left;
    width: calc(100% - 260px);
    :deep(.el-scrollbar__view) {
      // position: relative;
      // overflow: auto;
    }
    .filterHeader {
      @apply flex justify-between items-center mb-15px h-40px top-10px right-20px;
      position: fixed;
      z-index: 20;
    }
    .isFlexdBox {
      background-color: white;
      width: 100%;
      top: -2px;
      right: 20px;
      justify-content: end;
    }
  }
  .inputStyle {
    // height: ;
    line-height: 20px;
    border: 1px solid #ddd;
    width: 100%;
    border-radius: 3px;
    padding: 3px 10px;
    color: #606266;
  }
  .saveBtn {
    @apply absolute  bottom-0px;
    left: 50%;
    transform: translateX(-50%);
  }
  .dataList {
    height: calc(100vh - 70px);
    width: 100%;
    overflow-y: auto;
  }
  .control {
    // position: fixed;
    // right: 20px;
  }
}
:deep(.el-table__inner-wrapper) {
  height: 500px;
  overflow-y: auto;
}
:deep(.changeBorderColor) {
  border: 1px solid red !important;
}
</style>
